<?php

namespace card\api;

use card\models\Card;
use framework\common\BasicController;
use Yii;
use yii\data\ActiveDataProvider;

class IndexController extends BasicController
{
    /**
     * 重写父类
     * @return [type] [description]
     */
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        unset($actions['view']);
        unset($actions['create']);
        unset($actions['update']);
        return $actions;
    }

    public function actionSearch()
    {
        //获取头部信息
        $headers = Yii::$app->getRequest()->getHeaders();
        //获取分页信息
        $pageSize = $headers->get('X-Pagination-Per-Page') ?? 20;
        //订单分组
        $keyword = Yii::$app->request->post('keyword', []);
        $AppID = Yii::$app->params['AppID'];
        $where = ['card.AppID' => $AppID, 'card.is_deleted' => 0];

        //卡密批次ID
        $card_batch_id = $keyword['card_batch_id'] ?? '';
        if ($card_batch_id) {
            $where = ['and', $where, ['=', 'card.card_batch_id', $card_batch_id]];
        }

        //卡号
        $number = $keyword['number'] ?? '';
        if ($number) {
            $where = ['and', $where, ['like', 'card.number', $number]];
        }

        //是否绑定
        $is_bind = $keyword['is_bind'] ?? '';
        if ($is_bind !== '') {
            $where = ['and', $where, ['=', 'card.is_bind', $is_bind]];
        }

        //用户昵称
        $nickname = $keyword['nickname'] ?? '';
        if ($nickname) {
            $where = ['and', $where, ['like', 'user.nickname', $nickname]];
        }
        //用户UID
        $uid = !empty($keyword['uid']) ?$keyword['uid']: '';
        if ($uid) {
            $where = ['and', $where, ['=', 'user.id', $uid]];
        }

        //用户手机
        $mobile = $keyword['mobile'] ?? '';
        if ($mobile) {
            $where = ['and', $where, ['like', 'user.mobile', $mobile]];
        }

        //时间区间
        $expire_time_start = $keyword['expire_time_start'] ?? false;
        if ($expire_time_start > 0) {
            $where = ['and', $where, ['>=', 'card.begin_time', $expire_time_start]];
        }
        $expire_time_end = $keyword['expire_time_end'] ?? false;
        if ($expire_time_end > 0) {
            $where = ['and', $where, ['<=', 'card.end_time', $expire_time_end]];
        }

        //处理排序
        $sort = isset($keyword['sort']) && is_array($keyword['sort']) ? $keyword['sort'] : [];
        $orderBy = [];
        if (empty($sort)) {
            $orderBy = ['id' => SORT_ASC];
        } else {
            foreach ($sort as $key => $value) {
                $orderBy[$key] = $value === 'ASC' ? SORT_ASC : SORT_DESC;
            }
        }

        $data = new ActiveDataProvider(
            [
                'query' => Card::find()
                    ->alias('card')
                    ->joinWith([
                        'user as user',
                    ])
                    ->where($where)
                    ->orderBy($orderBy)
                    ->asArray(),
                'pagination' => ['pageSize' => $pageSize, 'validatePage' => false],
            ]
        );
        $list = $data->getModels();
//        foreach ($list as &$value) {
//            if ($value['is_used'] == 1) {
//                $value['status'] = 2;
//                $value['status_text'] = '已使用';
//            } elseif ($value['is_used'] == 0 && $value['end_time'] && $value['end_time'] < time()) {
//                $value['status'] = 3;
//                $value['status_text'] = '已过期';
//            } else {
//                $value['status'] = 1;
//                $value['status_text'] = '未使用';
//            }
//        }
        //将所有返回内容中的本地地址代替字符串替换为域名
        $list = str2url($list);
        $data->setModels($list);
        return $data;
    }

    public function actionView()
    {
        $id = Yii::$app->request->get('id', false);
        $where = ['id' => $id, 'is_deleted' => 0];
        $result = Card::find()
            ->where($where)
            ->with([
                'user',
            ])
            ->asArray()
            ->one();
        if (empty($result)) {
            Error('卡密不存在');
        }
//        if ($result['is_used'] == 1) {
//            $result['status'] = 2;
//            $result['status_text'] = '已使用';
//        } elseif ($result['is_used'] == 0 && $result['end_time'] && $result['end_time'] < time()) {
//            $result['status'] = 3;
//            $result['status_text'] = '已过期';
//        } else {
//            $result['status'] = 1;
//            $result['status_text'] = '未使用';
//        }
        $result = str2url($result);
        return $result;
    }

    /**
     * 处理数据软删除
     * @return [type] [description]
     */
    public function actionDelete()
    {

        $ids = \Yii::$app->request->get('id', false);
        $id = explode(',', $ids);
        Card::updateAll(['is_deleted' => 1, 'deleted_time' => time()], ['id' => $id]);
        return true;
    }

    /**
     * 批量修改号段
     * @return [type] [description]
     */
    public function changeNum()
    {
        $type = \Yii::$app->request->post('type', 0);//修改类型 0号段 1某些批量
        $num = \Yii::$app->request->post('num', 0);//增加金额
        $num = intval($num);
        if (empty($num) || $num <= 0){
            Error('增加金额不正确');
        }
        if ($type == 0){
            $start_num = \Yii::$app->request->post('start_num');
            $end_num = \Yii::$app->request->post('end_num');
            if (empty($start_num) || empty($end_num)){
                Error('请输入开始号段或者结束号段');
            }
            $start_id = Card::find()
                ->where(['number' => $start_num, 'is_deleted' => 0])
                ->asArray()
                ->one();
            if (empty($start_id)) {
                Error('开始号段不存在，请检查');
            }
            $end_id = Card::find()
                ->where(['number' => $end_num, 'is_deleted' => 0])
                ->asArray()
                ->one();
            if (empty($end_id)) {
                Error('结束号段不存在，请检查');
            }
            $where = ['and', ['>=', 'id', $start_id['id']], ['<=', 'id', $end_id['id']]];
        }else{
            $ids = \Yii::$app->request->post('ids');
            if (empty($ids)){
                Error('请选择需要修改的卡号');
            }
            $ids = explode(',', $ids);
            if (empty($ids)){
                Error('请选择需要修改的卡号');
            }
            $where = ['in', 'id', $ids];
        }
        Card::updateAll(['amount' => new \yii\db\Expression("amount+{$num}"), 'left_amount' => new \yii\db\Expression("left_amount+{$num}"), 'is_used' => 0], $where);
        return true;
    }
    /**
     * 批量修改号段
     * @return [type] [description]
     */
    public function changeStatus()
    {
        $type = \Yii::$app->request->post('type', 0);//修改类型 0号段 1某些批量
        $status = \Yii::$app->request->post('status', 0);//操作 1入库 2作废
        if (!in_array($status, [1, 2])){
            Error('操作类型不正确');
        }
        if ($type == 0){
            $start_num = \Yii::$app->request->post('start_num');
            $end_num = \Yii::$app->request->post('end_num');
            if (empty($start_num) || empty($end_num)){
                Error('请输入开始号段或者结束号段');
            }
            $start_id = Card::find()
                ->where(['number' => $start_num, 'is_deleted' => 0])
                ->asArray()
                ->one();
            if (empty($start_id)) {
                Error('开始号段不存在，请检查');
            }
            $end_id = Card::find()
                ->where(['number' => $end_num, 'is_deleted' => 0])
                ->asArray()
                ->one();
            if (empty($end_id)) {
                Error('结束号段不存在，请检查');
            }
            $where = ['and', ['>=', 'id', $start_id['id']], ['<=', 'id', $end_id['id']]];
        }else{
            $ids = \Yii::$app->request->post('ids');
            if (empty($ids)){
                Error('请选择需要修改的卡号');
            }
            $ids = explode(',', $ids);
            if (empty($ids)){
                Error('请选择需要修改的卡号');
            }
            $where = ['in', 'id', $ids];
        }
        Card::updateAll(['status' => $status], $where);
        return true;
    }
}
